package com.Xht.www.serviceImpl;
//处理需要联系用户与管理员的事务的接口的实现
import com.Xht.www.dao.UserWalletBalanceDAO;
import com.Xht.www.dao.WalletTransactionLogDAO;
import com.Xht.www.po.UserWalletBalancePO;
import com.Xht.www.po.WalletTransactionLogPO;
import com.Xht.www.service.UserAdmin;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;

public class UserAdminImpl implements UserAdmin {
    private final UserWalletBalanceDAO walletDao = new UserWalletBalanceDAO();
    private final WalletTransactionLogDAO logDao = new WalletTransactionLogDAO();

    @Override
    public boolean submitUserRecharge(int userId, BigDecimal amount, String reason) {
        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0 || reason == null || reason.isEmpty()) {
            return false;
        }
        UserWalletBalancePO wallet = walletDao.getUserByUserId(userId);
        if (wallet == null) {
            return false;
        }
        wallet.setTopUpAmount(amount);
        wallet.setRechargeReason(reason);
        wallet.setRechargeAuditStatus("审核中");
        return walletDao.updateUserWalletBalance(wallet);
    }

    @Override
    public List<UserWalletBalancePO> getPendingRecharges() {
        return walletDao.getAllPendingRecharges();
    }

    @Override
    public boolean approveRecharge(int walletId) {
        UserWalletBalancePO wallet = walletDao.getUserWalletBalance(walletId);
        if (wallet == null ||!"审核中".equals(wallet.getRechargeAuditStatus())) {
            return false;
        }
        BigDecimal topUpAmount = wallet.getTopUpAmount();
        wallet.setTotalAmount(wallet.getTotalAmount().add(topUpAmount));
        wallet.setRechargeAmount(wallet.getRechargeAmount().add(topUpAmount));
        wallet.setTopUpAmount(BigDecimal.ZERO);
        wallet.setRechargeAuditStatus("已通过");
        if (!walletDao.updateUserWalletBalance(wallet)) {
            return false;
        }
        // 插入交易日志，将transactionTime设置为当前时间
        WalletTransactionLogPO log = new WalletTransactionLogPO();
        log.setUserId(wallet.getUserId());
        log.setWalletId(walletId);
        log.setTransactionType("充值");
        log.setTransactionAmount(topUpAmount);
        log.setTransactionTime(new Timestamp(System.currentTimeMillis()));
        return logDao.insert(log);
    }

    @Override
    public boolean rejectRecharge(int walletId) {
        return walletDao.updateRechargeStatus(walletId, "未通过");
    }
}

